package com.example.springboot.service.admin.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.config.Shiro.security.SecurityUtil;
import com.example.springboot.mapper.CommentMapper;
import com.example.springboot.model.entity.Comment;
import com.example.springboot.model.form.PageUtil;
import com.example.springboot.model.form.Result;
import com.example.springboot.model.req.admin.CommentReq;
import com.example.springboot.model.sys.SysUser;
import com.example.springboot.model.vo.CommentVO;
import com.example.springboot.service.admin.CommentService;
import com.example.springboot.utils.CopyUtil;
import org.springframework.stereotype.Service;

/**
 * @author zf
 * @评论表
 * @since 2021-03-17
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {


    @Override
    public Result getPage(CommentReq req) {

        IPage<Comment> ipage = page(req.toPage(), new LambdaQueryWrapper<Comment>()
                .eq(Comment::getInvalid, 0)
                .orderByDesc(Comment::getCreateTime));

        Page<Comment> page = PageUtil.toPage(ipage);
        return Result.buildSuccess(PageUtil.convert(page, e -> {
            //主表复制元素
            CommentVO VO = CopyUtil.copyObject(e, CommentVO.class);
            return VO;
        }));
    }

    @Override
    public Result addInfo(CommentReq req) {
        SysUser sysUser = SecurityUtil.sysUser();
        Comment comment = CopyUtil.copyObject(req, Comment.class);
        comment.setAuthorId(sysUser.getId());
        boolean flag;
        if (req.getId() == null) {
            flag = save(comment);
        } else {
            flag = updateById(comment);
        }
        if (flag) {
            return Result.buildSuccess();
        }
        return Result.buildFail();
    }

    @Override
    public Result getInfo(Integer id) {
        return Result.buildSuccess(CopyUtil.copyObject(getById(id), CommentVO.class));
    }

    @Override
    public Result deleteInfos(String ids) {
        if (update(new UpdateWrapper<Comment>().lambda()
                .set(Comment::getInvalid, 1)
                .inSql(Comment::getId, ids)
        )) {
            return Result.buildSuccess();
        }
        return Result.buildFail();
    }

}
